package com.sell.service.impl;

import com.sell.dto.OrderDTO;
import com.sell.exceptions.ResultEnum;
import com.sell.exceptions.SellException;
import com.sell.service.BuyerService;
import com.sell.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: megan
 * @eMail: meganmail@vip.qq.com
 * @date: 2018/12/7 14:00
 * @version: v1.0
 * @description:
 */
@Slf4j
@Service
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        OrderDTO orderDTO = orderService.findOne(orderId);
        return checkOrderOwner(orderDTO, openid);
    }

    @Override
    public OrderDTO cancelOrder(OrderDTO orderDTO, String openid) {
        OrderDTO resultDTO = orderService.cancel(orderDTO);
        return checkOrderOwner(resultDTO, openid);
    }

    /**
     * 比较openid 是否一致
     *
     * @param orderDTO
     * @param openid
     * @return
     */
    private OrderDTO checkOrderOwner(OrderDTO orderDTO, String openid) {
        if (orderDTO == null) {
            log.error("【订单查询】订单不存在");
            return null;
        }
        if (!StringUtils.equals(orderDTO.getBuyerOpenid(), openid)) {
            log.error("[查询订单]订单的openid不一致");
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
